package com.lsfb.signln.Location;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.lsfb.signln.Location.LocationSearch.LocationSearchActivity;
import com.lsfb.signln.Location.SignIn.SignEvent2;
import com.lsfb.signln.Location.SignIn.SignInActivity;
import com.lsfb.signln.Location.TaskMsg.TaskMsgActivity;
import com.lsfb.signln.Login.LoginActivity;
import com.lsfb.signln.R;
import com.lsfb.signln.Utils.LittleUtils;
import com.lsfb.signln.Utils.MyProgressDialog;
import com.lsfb.signln.Utils.URLString;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.LsfbFragment;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInjectUtils;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.SPUtils;
import com.zgscwjm.lsfbbasetemplate.utils.T;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;


/**
 * Created by Administrator on 2018/1/23 0023.
 */

public class LocationFragment extends LsfbFragment {

    private View view;

    /**
     * activity对象
     */
    private Activity mactivity;

    /**
     * 消息数
     */
    @ViewInject(R.id.fg_text_badgview)
    private TextView text_badgview;

    /**
     * 定位地址
     */
    @ViewInject(R.id.fg_home_text_address)
    private TextView text_address;

    /**
     * 时间
     */
    @ViewInject(R.id.fg_home_text_time_now)
    private TextView text_time_now;

    /**
     * 今日定位状态
     */
    @ViewInject(R.id.fg_text_location_state)
    private TextView text_location_state;

    /**
     * 今日定位时间
     */
    @ViewInject(R.id.fg_text_location_time)
    private TextView text_location_time;

    @ViewInject(R.id.fg_img_singin)
    private ImageView fg_img_singin;

    /**
     * 晚间定位
     */
    @ViewInject(R.id.fg_wanshang_singin)
    private ImageView fg_wanshang_singin;

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();

    /**
     * 地图
     */
    @ViewInject(R.id.bmapView)
    private MapView mMapView;

    /**
     * 百度
     */
    private BaiduMap mBaiduMap;
    private BitmapDescriptor mCurrentMarker;

    /**
     * 人脸识别结果
     */
    private String filePath;

    /**
     * 省市区行政编码
     */
    private String adcode;
    /**
     * 城市编码
     */
    private String citycode;

    /**
     * 时间获取工具类
     */
    private Calendar calendar;

    private MyProgressDialog dialog;

    private int year;
    private int month;
    private int day;
    private int week;
    private String isNightArray;

    private NotificationManager mNotifiManager;

    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case 1000:
                    calendar = Calendar.getInstance(Locale.CHINA);
                    year = calendar.get(Calendar.YEAR); //获取Calendar对象中的年
                    month = calendar.get(Calendar.MONTH);//获取Calendar对象中的月
                    day = calendar.get(Calendar.DAY_OF_MONTH);//获取这个月的第几天
                    week = calendar.get(calendar.DAY_OF_WEEK);//获取今天是这周的第几天，星期天为第一天

                    switch (week) {
                        case 1:
                            text_time_now.setText("星期日  " + year + "年" + (month + 1) + "月" + day + "日");
                            break;
                        case 2:
                            text_time_now.setText("星期一  " + year + "年" + (month + 1) + "月" + day + "日");
                            break;
                        case 3:
                            text_time_now.setText("星期二  " + year + "年" + (month + 1) + "月" + day + "日");
                            break;
                        case 4:
                            text_time_now.setText("星期三  " + year + "年" + (month + 1) + "月" + day + "日");
                            break;
                        case 5:
                            text_time_now.setText("星期四  " + year + "年" + (month + 1) + "月" + day + "日");
                            break;
                        case 6:
                            text_time_now.setText("星期五  " + year + "年" + (month + 1) + "月" + day + "日");
                            break;
                        case 7:
                            text_time_now.setText("星期六  " + year + "年" + (month + 1) + "月" + day + "日");
                            break;
                    }
                    break;
            }
        }
    };


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_location, null);
            ViewInjectUtils.inject(this, view);
        }

        validSign();
        getMsgCount();
        mNotifiManager = (NotificationManager) mactivity.getSystemService(Context.NOTIFICATION_SERVICE);

        mLocationClient = new LocationClient(mactivity.getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        initLocation();
        mLocationClient.start();


        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setCompassEnable(false);

//        mMapView.showScaleControl(false);
        mMapView.showZoomControls(false);
//        UiSettings settings = mBaiduMap.getUiSettings();
//        settings.setAllGesturesEnabled(false);   //关闭一切手势操作

        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        dialog = new MyProgressDialog(mactivity, "请稍等...");
        return view;
    }

    /**
     * 获取消息数
     */
    private void getMsgCount() {
        HashMap hashMap = new HashMap();
        new BaseInternet().getData_Get(URLString.COUNTMSG, hashMap, String.class, new MsgCountEvent<String>(), true, false);
    }

    @EventAnnotation
    public void eventResult(MsgCountEvent<String> event) {
        switch (event.getCode()) {
            case 200:
                if (event.getData().equals("0") || event.getData() == null) {
                    text_badgview.setVisibility(View.INVISIBLE);
                } else {
                    text_badgview.setText(event.getData());
                }
                break;
            case 1006:
                T.showShort(mactivity, "您的账户已在其它设备登录，请重登录");
                LittleUtils.exit(mactivity);
                startActivity(new Intent(mactivity, LoginActivity.class));
                break;
            default:
                T.showShort(getActivity(), event.getMsg());
                break;
        }
    }

    private void validSign() {
        HashMap hashMap = new HashMap();
        new BaseInternet().getData(URLString.VALIDSIGN, hashMap, ValidSignBean.class, new ValidSignEvent<ValidSignBean>(), true);
    }

    @EventAnnotation
    public void eventResult(ValidSignEvent<ValidSignBean> event) {
        switch (event.getCode()) {
            case 200:
                switch (event.getData().getState()) {
                    case 0:
                        text_location_state.setText("今日未定位");
                        text_location_time.setVisibility(View.INVISIBLE);
                        fg_wanshang_singin.setVisibility(View.VISIBLE);

                        String startTime = event.getData().getStartTime();
                        String endTime = event.getData().getEndTime();
                        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
                        try {
                            Date date = new Date();
                            String sdf_date = df.format(date);
                            Date start_date = df.parse(startTime);
                            Date end_date = df.parse(endTime);
                            Date current_date = df.parse(sdf_date);
                            if (current_date.getTime() >= start_date.getTime() && current_date.getTime() <= end_date.getTime()) {
                                fg_wanshang_singin.setVisibility(View.VISIBLE);
                            } else {
                                fg_wanshang_singin.setVisibility(View.GONE);
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        break;
                    case 1:
                        text_location_state.setText("今日已定位");
                        text_location_time.setVisibility(View.VISIBLE);
                        text_location_time.setText("定位时间：" + event.getData().getTime());
                        fg_wanshang_singin.setVisibility(View.GONE);
                        fg_wanshang_singin.setVisibility(View.GONE);
                        break;
                }
                break;
            case 1006:
                T.showShort(mactivity, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(mactivity);
                startActivity(new Intent(mactivity, LoginActivity.class));
                break;
            default:
                T.showShort(getActivity(), event.getMsg());
                break;
        }
    }

    /**
     * 百度定位设置
     */
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认gcj02
        //gcj02：国测局坐标；
        //bd09ll：百度经纬度坐标；
        //bd09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标

        option.setScanSpan(1000);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false
        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            LsfbLog.e("adcode：" + location.getAdCode() + "citycode：" + location.getCityCode() + "经纬度：" + location.getLatitude() + ";" + location.getLongitude());
            if (location.getAdCode() != null) {
                adcode = location.getAdCode();
            } else {
                adcode = "0";
            }
            if (location.getCityCode() != null) {
                citycode = location.getCityCode();
                SPUtils.put(mactivity, "citycode", location.getCityCode());
                if (!SPUtils.get(mactivity, "citycode", "").equals(location.getCityCode()) && !SPUtils.get(mactivity, "citycode", "").equals("0")){
                      //发送通知
                    CreateInform();
                }
            } else {
                citycode = "0";
                SPUtils.put(mactivity, "citycode", "0");
            }

            text_address.setText(location.getAddrStr());
            // 构造定位数据
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();

            // 设置定位数据
            mBaiduMap.setMyLocationData(locData);

            // 当不需要定位图层时关闭定位图层
//            mBaiduMap.setMyLocationEnabled(false);

            LatLng ll = new LatLng(location.getLatitude(),
                    location.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(18.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory
                    .newMapStatus(builder.build()));

            mLocationClient.stop();
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mactivity = activity;
    }

    /**
     * 发送通知
     */
    public void CreateInform() {
        Notification.Builder builder = new Notification.Builder(mactivity);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setTicker("您所在城市位置发生了改变");
        builder.setContentTitle("温馨提示");
        builder.setContentText("您所在城市位置发生了改变");
        builder.setWhen(System.currentTimeMillis()); //发送时间
        builder.setDefaults(Notification.DEFAULT_ALL);
        Notification notification = builder.build();
        notification.defaults = Notification.DEFAULT_SOUND;
        mNotifiManager.notify(123, notification);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.fg_img_search, R.id.fg_img_msg, R.id.fg_location_refresh, R.id.fg_img_singin, R.id.fg_wanshang_singin})
    public void onClick(View view) {
        switch (view.getId()) {
            //定位查询
            case R.id.fg_img_search:
                startActivity(new Intent(mactivity, LocationSearchActivity.class));
                break;
            //消息
            case R.id.fg_img_msg:
                startActivity(new Intent(mactivity, TaskMsgActivity.class));
                break;
            //刷新
            case R.id.fg_location_refresh:
                mLocationClient.start();
                T.showShort(mactivity, "定位中...");
                break;
            //定位
            case R.id.fg_img_singin:
                ckFaceauth();
                isNightArray = "0";
                break;
            //凌晨定位
            case R.id.fg_wanshang_singin:
                ckFaceauth();
                isNightArray = "1";
                break;
        }
    }

    /**
     * 是否需要人脸识别
     */
    public void ckFaceauth() {
//        dialog.showdialog();
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("adcode", adcode);
        new BaseInternet().getData(URLString.CKFACEAUTH, hashMap, String.class, new CkFaceauthEvent(), true);
    }

    @EventAnnotation
    public void CkFaceauthEvent(CkFaceauthEvent event) {
        switch (event.getCode()) {
            case 200:
                if (event.getData() != null && !event.getData().isEmpty()) {
                    startActivity(new Intent(mactivity, SignInActivity.class).putExtra("adcode", adcode).putExtra("citycode", citycode).putExtra("token", event.getData()));
                } else {
                    sign();
                }
                break;
            case 1006:
                T.showShort(mactivity, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(mactivity);
                startActivity(new Intent(mactivity, LoginActivity.class));
                break;
            default:
                T.showLong(mactivity, "系统出错，定位信息异常");
                break;
        }
    }

    /**
     * 定位
     */
    public void sign() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("cityCode", citycode);
        hashMap.put("adcode", adcode);
        hashMap.put("signType", "0");
        hashMap.put("isNightArray", isNightArray);
        new BaseInternet().getData(URLString.SIGN, hashMap, String.class, new SignEvent2(), true);
    }

    @EventAnnotation
    public void SignEvent(SignEvent2 event) {
//        dialog.hidedialog();
        switch (event.getCode()) {
            case 200:
                T.showShort(mactivity, "定位成功");
                break;
            case 1006:
                T.showShort(mactivity, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(mactivity);
                startActivity(new Intent(mactivity, LoginActivity.class));
                break;
            default:
                T.showLong(mactivity, event.getMsg());
                break;
        }
    }

    @Override
    protected void Resume() {
        validSign();
        getMsgCount();
    }

    @Override
    public void initData() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        if (mMapView != null) {
            mMapView.onDestroy();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        if (mMapView != null) {
            mLocationClient.start();
            mMapView.onResume();
        }
        handler.sendEmptyMessageDelayed(1000, 500);
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (mMapView != null) {
            mMapView.onPause();
        }
    }
}
